using System;
using System.Data;
using System.Data.SqlClient;
using System.Threading;

namespace OneDayModel.DBRepository.MSSQL
{
    public class SqlConnectionManager : IConnectionManager, IDisposable
    {
        private readonly string connectionString;
        private static int connectionsCount = 0;
        private static SqlConnection connectionForPooling = null;

        public SqlConnectionManager(string connectionString)
        {
            this.connectionString = connectionString;
            OpenConnectionForPooling();
        }

        private void OpenConnectionForPooling()
        {
            if (connectionString != null)
            {
                connectionForPooling = new SqlConnection(connectionString);
                connectionForPooling.Open();
            }
        }

        private void CloseConnectionForPooling()
        {
            if ((connectionForPooling != null) && (connectionForPooling.State == ConnectionState.Open))
                connectionForPooling.Close();
            connectionForPooling = null;
        }

        public IDbConnection AcquireConnection()
        {
            SqlConnection connection;
            if (Interlocked.Increment(ref connectionsCount) == 1)
                connection = connectionForPooling;
            else
            {
                connection = new SqlConnection(connectionString);
                connection.Open();
            }
            return connection;
        }

        public void ReleaseConnection(IDbConnection dbConnection)
        {
            if (Interlocked.Decrement(ref connectionsCount) > 1)
                dbConnection.Close();
        }

        public void Dispose()
        {
            CloseConnectionForPooling();
        }
    }
}